<?php namespace App\Admin\Cabinet\CabinetCell\Listeners;

use Log;
use DB;
use App\Core\Service\Listeners\UpdateListener as Base;

class UpdateListener extends Base {

    public $uqKey = '2E74033947A3B8962352EE519C0415A8';

    public function onUpdateSaved(){
        $code = $this->service->updateModel->code;
        $rfid = $this->service->updateModel->rfid;
        if(!$code || !$rfid){
            return;
        }
        $cabinet_id =  $this->service->updateModel->cabinet_id;
        $cabinet = DB::table('cabinet')->select('id','code')
            ->where('id','=',$cabinet_id)
            ->first();
        if(!$cabinet){
            return;
        }
        $eno = $cabinet->code;
        $this->setRfid($eno,$code,$rfid);
    }
    //设置rfid
    public function setRfid($eno,$bno,$rfid){
        $url = 'http://cos.wondware.com/mq/device/screen/sendMajorInfo';
        $msg = array(
            'massage'=>'setRfid',
            'lockAddr'=>$bno,
        );
        if(is_array($rfid)){
            $i = 0;
            foreach ($rfid as $key => $value) {
                $i++;
                $index_key = 'rfid'.$i;
                $msg[$index_key] = str_replace(' ', '', $value);
            }
        } else {
            $msg['rfid1'] =  str_replace(' ', '', $rfid);
        }
        $jsonData = json_encode($msg);
        $post_data['deviceId']       = $eno;
        $post_data['uqKey']    = $this->uqKey;
        $post_data['jsonData']    = $jsonData;
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = $this->request_post($url, $post_data);
        return $res;
    }
    //post
    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
}